#include "Reactor/TcpConnection.h"
#include "Reactor/EchoServer.h"
#include "Mylogger.hh"
#include "Dictionary/KeyRecommander.h"
#include "servicecode/HttpResponse.h"
#include "servicecode/HttpRequest.h"
#include "servicecode/MyTask.h"
#include <iostream>
#include <functional>

using std::bind;
using std::cout;
using std::endl;

EchoServer::EchoServer(size_t threadNum, size_t queSize, const string &ip, unsigned short port)
    : _pool(threadNum, queSize), _server(ip, port)
{
}

EchoServer::~EchoServer()
{
}

// 服务器的启动与停止
void EchoServer::start()
{
    _pool.start();

    // 三个回调放在此处进行注册
    using namespace std::placeholders;
    _server.setAllCallback(bind(&EchoServer::onNewConnection, this, _1), bind(&EchoServer::onMessage, this, _1), bind(&EchoServer::onClose, this, _1));
    _server.start();
}

void EchoServer::stop()
{
    LogDebug("EchoServer stop");
    _pool.stop();
    _server.stop();
}

// 三个回调
void EchoServer::onNewConnection(const TcpConnectionPtr &con)
{
    LogInfo("有新的客户端连接 %s", con->get_peerAddr().c_str());
}

void EchoServer::onMessage(const TcpConnectionPtr &con)
{
    string msg = con->receive();
    con->addbuffer(msg);//将信息放入缓冲区
    if (con->getbuffer().find("\r\n\r\n") != std::string::npos)
    {
        // 生成http请求
        HttpRequest httpreq(con->getbuffer());
        LogDebug("生成http请求:%s", httpreq.gethttprequest().c_str());
        con->clearbuffer();
        MyTask task(httpreq, con);
        _pool.addTask(bind(&MyTask::process, task));
    }
}

void EchoServer::onClose(const TcpConnectionPtr &con)
{
    cout << con->get_peerAddr() << " has closed!!!" << endl;
}